﻿// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System;
using System.IO;
using System.Web.Caching;
using System.Web.Hosting;
using System.Xml.Serialization;

namespace BlueOnionSoftware.Bloget.Utility
{
    internal sealed class Serializer
    {
        internal static T Load<T>(string filename, string @namespace) where T : class
        {
            Throw.IfNullOrEmpty(filename, "filename");
            Throw.IfNullOrEmpty(@namespace, "@namespace");

            var item = HostingEnvironment.Cache[filename] as T;

            if (item == null)
            {
                using (var stream = File.OpenRead(filename))
                {
                    var xs = new XmlSerializer(typeof (T), @namespace);
                    item = (T) xs.Deserialize(stream);
                }

                HostingEnvironment.Cache.Insert(filename, item, new CacheDependency(Path.GetFullPath(filename)),
                                                Cache.NoAbsoluteExpiration, new TimeSpan(0, 1, 0), CacheItemPriority.BelowNormal, null);
            }

            return item;
        }

        internal static void Save<T>(string filename, string @namespace, object item)
        {
            Throw.IfNullOrEmpty(filename, "filename");
            Throw.IfNullOrEmpty(@namespace, "@namespace");
            Throw.IfNull(item, "item");

            using (Stream memory = new NonContiguousMemoryStream())
            {
                using (var stream = new StreamWriter(memory))
                {
                    var xs = new XmlSerializer(typeof (T), @namespace);
                    xs.Serialize(stream, item);
                    stream.Flush();
                    memory.Position = 0;
                    FileUtilities.WriteFile(filename, memory);
                }
            }

            HostingEnvironment.Cache.Insert(filename, item, new CacheDependency(Path.GetFullPath(filename)),
                                            Cache.NoAbsoluteExpiration, new TimeSpan(0, 1, 0), CacheItemPriority.BelowNormal, null);
        }
    }
}